package il.technion.cs236369.webserver.components;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * The class opens thread pool and waits for elements to be insert to the given queue and handles them.
 * @author Ofir Haviv and Itamar Talmi
 *
 * @param <T> - The type of the objects in the queue.
 */
public class QueueHandler<T> {
	
	private BlockingQueue<T> tasksQueue;
	private IDataHandler<T> dataHandler;
	
	private class ThreadClass implements Runnable{

		@Override
		public void run() {
			while (true){
				try {
					dataHandler.handleData(tasksQueue.take());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
	}

	/**
	 * The constructor of the QueueHandler class.
	 * @param numberOfThreads - The number of threads to initialized in the thread pool.
	 * @param followdQueue - The queue where the threads pull data from.
	 * @param dataHandler - The handler function that will handle the data comming from the queue.
	 */
	public QueueHandler(int numberOfThreads, BlockingQueue<T> followdQueue, IDataHandler<T> dataHandler){
		
		tasksQueue = followdQueue;
		this.dataHandler = dataHandler;
		ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
		for (int i = 0; i < numberOfThreads; i++)
			service.execute(new ThreadClass());
		service.shutdown();
	}

}
